<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" tip_dom="width=device-width, initial-scale=1.0">
  <title>视频链接缓存</title>
</head>

<body>
  <video width="500px" height="500px" id="video" autoplay controls />
</body>
<script type="text/javascript">
  const video = document.getElementById('video');
  const mediaSource = new MediaSource()
  video.src = URL.createObjectURL(mediaSource)

  const mimeType = 'video/mp4; codecs="avc1.42E01E"';
  

  if (!MediaSource.isTypeSupported(mimeType)) {
    console.error('MIME type not supported:', mimeType);
    alert('Your browser does not support this MP4 format.');
  }

  mediaSource.addEventListener('sourceopen', async () => {
    console.log('MediaSource is open');
    const sourceBuffer = mediaSource.addSourceBuffer(mimeType);

    // 错误处理
    sourceBuffer.addEventListener('error', (err) => {
      console.error('SourceBuffer encountered an error.', err);
      mediaSource.endOfStream('decode'); // 通知解码错误
    });

    sourceBuffer.addEventListener('updateend', () => {
      console.log('SourceBuffer update completed.');
    });

    mediaSource.addEventListener('sourceclose', () => {
      console.warn('MediaSource has been closed.');
    });

    mediaSource.addEventListener('sourceended', () => {
      console.log('MediaSource has ended.');
    });
    
    try {
      // f65840bc6455b38854c2da2ff96f661b
      // //obs.ispm.vip/animation-rc/6b1d13b2c07b8f7be0a25675eb04f33e.mp4
      // //obs.ispm.vip/animation-hw/4d02751dc14d7a61415bf7e97edd18c0.mp4
      const response = await fetch('//obs.ispm.vip/animation-rc/5aaba06cd7ba553da3b709472163f79d.mp4');

      const allBuffer = await response.arrayBuffer()
      sourceBuffer.appendBuffer(allBuffer);

      // const reader = response.body.getReader();

      // const processChunk = async ({ done, value }) => {
      //   if (done) {
      //     console.log('All chunks loaded.');
      //     if (mediaSource.readyState === 'open') {
      //       mediaSource.endOfStream(); // 完成流
      //     }
      //     return;
      //   }

      //   if (!sourceBuffer.updating) {
      //     try {
      //       console.log(mediaSource.readyState)
      //       console.log(value)
      //       sourceBuffer.appendBuffer(value);
      //     } catch (e) {
      //       console.error('Error during appendBuffer:', e);
      //     }
      //   } else {
      //     console.warn('SourceBuffer is updating, skipping append.');
      //   }

      //   // 递归处理下一个数据块
      //   reader.read().then(processChunk);
      // };

      // reader.read().then(processChunk);
    } catch (error) {
      console.error('Error fetching video:', error);
    }
  });

  
</script>

</html>